package com.snails.tool.app;

/**
 * activity堆栈管理
 * @author lawrence
 */
import android.app.Activity;

import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Set;
import java.util.Stack;

public final class ActivityStackManager {
    private static volatile ActivityStackManager instance = null;

    private Stack<WeakReference<Activity>> stack;

    public static ActivityStackManager instance() {
        if (instance == null) {
            synchronized (ActivityStackManager.class) {
                if (instance == null)
                    instance = new ActivityStackManager();
            }
        }
        return instance;
    }

    // ================================================================================
    // --- ---
    // ================================================================================
    private ActivityStackManager() {
        stack = new Stack<>();
    }

    /**
     * 从栈中清理掉已释放的引用
     */
    private void cleanNull() {
        if (!stack.empty()) {
            // 使用迭代器进行安全删除
            Iterator<WeakReference<Activity>> iterator = stack.iterator();
            while (iterator.hasNext()) {
                WeakReference<Activity> weakReference = iterator.next();
                Activity activity = weakReference.get();
                if (activity == null) { iterator.remove(); }
            }
        }
    }

    // ================================================================================
    // --- ---
    // ================================================================================
    /**
     * 向栈中添加activity
     */
    public void add(Activity activity) {
        stack.add(new WeakReference<>(activity));
    }

    /**
     * 从栈中移除activity
     */
    public void remove(Activity activity) {
        if (activity != null && !stack.empty()) {
            Iterator<WeakReference<Activity>> iterator = stack.iterator();
            while (iterator.hasNext()) {
                WeakReference<Activity> weakReference = iterator.next();
                Activity temp = weakReference.get();
                if (temp == null) {
                    // 从栈中清理掉已释放的引用
                    iterator.remove(); continue;
                }
                if (temp == activity) {
                    // 从栈中移除指定activity
                    iterator.remove(); break;
                }
            }
        }
    }

    /**
     * 从栈中移除指定类名的Activity
     * @return 返回cls对应的Activity，未找到返回null
     */
    public Activity remove(Class<?> cls) {
        Activity result = null;
        if (!stack.empty()) {
            Iterator<WeakReference<Activity>> iterator = stack.iterator();
            while (iterator.hasNext()) {
                WeakReference<Activity> weakReference = iterator.next();
                Activity temp = weakReference.get();
                if (temp == null) {
                    // 从栈中清理掉已释放的引用
                    iterator.remove(); continue;
                }
                if (temp.getClass().equals(cls)) {
                    // 从栈中移除指定类名的Activity
                    iterator.remove(); result = temp; break;
                }
            }
        }
        return result;
    }

    /**
     * 从栈中移除activity，并关闭activity
     */
    public void finish(Activity activity) {
        if (activity != null && !stack.empty()) {
            remove(activity);
            activity.finish();
        }
    }

    /**
     * 从栈中移除activity，并关闭activity
     */
    public void finish(Class<?> cls) {
        if (!stack.empty()) {
            Activity result = remove(cls);
            if (result != null) { result.finish(); }
        }
    }

    /**
     * 从栈中移除所有指定activity，并关闭activity
     */
    public void finish(Set<Class<?>> clazz) {
        if (!stack.empty() && clazz != null && !clazz.isEmpty()) {
            Iterator<WeakReference<Activity>> iterator = stack.iterator();
            while (iterator.hasNext()) {
                WeakReference<Activity> weakReference = iterator.next();
                Activity temp = weakReference.get();
                if (temp == null) {
                    // 从栈中清理掉已释放的引用
                    iterator.remove(); continue;
                }
                if (clazz.contains(temp.getClass())) {
                    iterator.remove();
                    temp.finish();
                    clazz.remove(temp.getClass());
                }
                if (clazz.isEmpty()) { break; }
            }
        }
    }

    /**
     * 从栈中移除所有activity，并关闭activity
     */
    public void finishAll() {
        if (!stack.empty()) {
            Iterator<WeakReference<Activity>> iterator = stack.iterator();
            while (iterator.hasNext()) {
                WeakReference<Activity> weakReference = iterator.next();
                Activity temp = weakReference.get();
                if (temp != null && !temp.isFinishing()) { temp.finish(); }
            }
            stack.clear();
        }
    }

    /**
     * 获取当前Activity（栈中最后一个压入的）
     */
    public Activity current() {
        cleanNull();
        if (!stack.empty() && !stack.isEmpty()) {
            return stack.lastElement().get();
        }
        return null;
    }

    /**
     * 退出应用程序
     */
    public void exitApp() {
        try {
            finishAll();
            // 退出JVM,释放所占内存资源,0表示正常退出
            System.exit(0);
            // 从系统中kill掉应用程序
            android.os.Process.killProcess(android.os.Process.myPid());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
